<?php

namespace App\Services\Admin;

use App\Models\MsgGroup;
use Illuminate\Support\Facades\Log;
use App\Models\MsgInfo;
use Illuminate\Support\Facades\DB;
use App\Services\Api\PushService;
use App\Jobs\AsyncSendMsgNotice;

class MessageService extends AdminService{


    /**
     * 获取列表
     * @param [type] $page
     * @param [type] $per_page
     * @method getList
     * @author chengzhigang<1256699215@qq.com>
     */
    public function getList($page,$per_page){
        try{
            $where = [];
            $where[] = ['status','<>',3];
            $data = MsgInfo::where($where)->paginate($per_page,['*'],'page',$page)->toArray();
            foreach($data['data'] as &$val){
                $val['send_msg'] = MsgInfo::sendStatus($val['status']);
                $val['user_type_msg'] = MsgInfo::userStatus($val['user_type']);
                $val['type_msg'] = MsgInfo::getTypeConfig($val['type'])['title'];
            }
            return ['status'=>1,'msg'=>'请求成功','data'=>$data];
        }catch(\Exception $e){
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('消息列表：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    public function createMsg($data){
        try{
            $msgData = [];
            $msgData['title'] = $data['title'];
            $msgData['content'] = $data['content'];
            if(!isset($data['user'])){
                $data['user'] = [];
            }
            if(isset($data['logo'])&&!empty($data['logo'])){
                //上传logo
                $dir = 'uploads/message';
                $result = upload($data['logo'],'image',['dir'=>$dir]);
                if($result['status']==2){
                    return ['status'=>2,'msg'=>$result['msg'],'data'=>[]];
                }
                $msgData['logo'] = $result['data'];
            }
            if($data['user_type']==2&&empty($data['user'])){
                return ['status'=>2,'msg'=>'请选择用户','data'=>[]];
            }
            if(empty($data['send_time'])){
                $msgData['send_time'] = date('Y-m-d H:i:s');
                $msgData['status'] = 2;//即时发送
                $expire = 1;
            }else{
                if(strtotime($data['send_time'])<time()){
                    return ['status'=>2,'msg'=>'发送时间不合规','data'=>[]];
                }
                $msgData['send_time'] = $data['send_time'];
                $msgData['status'] = 1;//定时发送
                $expire = strtotime($data['send_time'])-time();
            }
            $msgData['type'] = $data['type'];
            $msgData['detail'] = $data['detail'];
            $msgData['url'] = $data['url'];
            $msgData['user_type'] = $data['user_type'];
            $msgData['create_id'] = auth('admin')->user()->id;
            DB::beginTransaction(); //开启事务
            $msgModel = MsgInfo::create($msgData);
            if(!$msgModel){
                throw new \Exception('创建消息失败');
            }
            foreach($data['user'] as $v){
                $groupModel = MsgGroup::create(['user_id'=>$v,'msg_id'=>$msgModel->id]);
                if(!$groupModel){
                    throw new \Exception('创建消息群组失败');
                }
            }
            DB::commit();
            //推送通知
            $msgData['id'] = $msgModel->id;
            if(empty($msgData['logo'])){
                $msgData['logo'] = MsgInfo::getTypeConfig($msgData['type'])['logo'];
            }else{
                $msgData['logo'] = config('const.img_url').$msgData['logo'];
            }
            $msgData['payload'] = $msgData;
            dispatch(new AsyncSendMsgNotice($msgData,$data['user'], $expire));
            return ['status'=>1,'msg'=>'创建成功','data'=>[]];
        }catch(\Exception $e){
            DB::rollback();
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('创建消息：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    public function updateMsg($data){
        try{
            $msgData = [];
            $msgData['title'] = $data['title'];
            $msgData['content'] = $data['content'];
            if(!isset($data['user'])){
                $data['user'] = [];
            }
            if(isset($data['logo'])&&!empty($data['logo'])){
                if(is_string($data['logo'])){
                    $msgData['logo'] = $data['logo'];
                }else{
                    //上传logo
                    $dir = 'uploads/message';
                    $result = upload($data['logo'],'image',['dir'=>$dir]);
                    if($result['status']==2){
                        return ['status'=>2,'msg'=>$result['msg'],'data'=>[]];
                    }
                    $msgData['logo'] = $result['data'];
                }
            }
            if($data['user_type']==2&&empty($data['user'])){
                return ['status'=>2,'msg'=>'请选择用户','data'=>[]];
            }
            if(empty($data['send_time'])){
                $msgData['send_time'] = date('Y-m-d H:i:s');
                $msgData['status'] = 2;//即时发送
            }else{
                if(strtotime($data['send_time'])<time()){
                    return ['status'=>2,'msg'=>'发送时间不合规','data'=>[]];
                }
                $msgData['send_time'] = $data['send_time'];
                $msgData['status'] = 1;//定时发送
            }
            $msgData['type'] = $data['type'];
            $msgData['detail'] = $data['detail'];
            $msgData['url'] = $data['url'];
            $msgData['user_type'] = $data['user_type'];
            DB::beginTransaction(); //开启事务
            $msgModel = MsgInfo::where('id',$data['id'])->update($msgData);
            //删除绑定关系
            MsgGroup::where('msg_id',$data['id'])->delete();
            foreach($data['user'] as $v){
                MsgGroup::create(['user_id'=>$v,'msg_id'=>$data['id']]);
            }
            DB::commit();
            //推送通知
            if($msgData['status']==2){
                $pushService = new PushService();
                $msgData['id'] = $msgModel->id;
                if(empty($msgData['logo'])){
                    $msgData['logo'] = MsgInfo::getTypeConfig($msgData['type'])['logo'];
                }else{
                    $msgData['logo'] = config('const.img_url').$msgData['logo'];
                }
                $msgData['payload'] = $msgData;
                $result = $pushService->push($msgData,$msgData['user_type'],$data['user']);
            }
            return ['status'=>1,'msg'=>'编辑成功','data'=>[]];
        }catch(\Exception $e){
            DB::rollback();
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('编辑消息：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }
}
